"""
服务开启与关闭时触发事件
"""

# import asyncio
# import logging

from sanic.log import error_logger, logger

from server.middleware import init_db_session, close_db_session
from server.logger import setup_logger


def access_filter(record):
    """
    access_filter
    """
    if hasattr(record, "request"):
        record.request_host = "HOST " + record.host + " "
        record.request_url = record.request + " "
        record.request_status = record.status
    else:
        record.request_url = ""
        record.request_host = ""
        record.request_status = ""
    return True


async def before_app_start(app, loop):
    """
    before_server_start
    """
    if app.config.ACCESS_LOG:
        handler = setup_logger(app)

        # 全局配置
        # logging.basicConfig(handlers=[handler])
        logger.addHandler(handler)

    # # 更新数据库版本文件
    # cmd = f'cd {app.config.BASE_DIR} && /usr/local/bin/alembic upgrade head'
    # proc = await asyncio.subprocess.create_subprocess_shell(
    #     cmd,
    #     stdout=asyncio.subprocess.PIPE,
    #     stderr=asyncio.subprocess.PIPE,
    # )
    # stdout, stderr = await proc.communicate()
    # logger.info('alembic upgrade head cmd: {}, code: {}'.format(cmd, proc.returncode))
    # if stdout:
    #     logger.info(f'alembic upgrade head stdout:\n{stdout.decode()}')
    # if stderr:
    #     logger.info(f'alembic upgrade head stderr:\n{stderr.decode()}')


async def after_app_start(app, loop):
    """
    after_vmware_start
    """
    try:
        await init_db_session(app, loop)
    except Exception as ex:
        error_logger.error("init db session error：%s", ex)


async def before_app_stop(app, loop):
    """
    before_server_stop
    """
    try:
        await close_db_session(app)
    except Exception as ex:
        error_logger.error("close db session error:%s", ex)


async def after_app_stop(app, loop):
    """
    after_server_stop
    """
    logger.info("after app stop ...")
